package com.df.happylearn.utils;

import android.content.Context;

import com.df.happylearn.application.MyApplication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class CssUtil {

    Context context;
    private static CssUtil cssUtil = null;
    private String css = null;

    public static synchronized CssUtil getInstance() {
        if (cssUtil == null) {
            cssUtil = new CssUtil(MyApplication.getInstance());
        }
        return cssUtil;
    }

    public CssUtil(Context context) {
        this.context = context;
    }

    /**
     * 读取css文件内容
     *
     * @return
     */
    private String buildCss() {
        StringBuilder contents = new StringBuilder();
        InputStreamReader reader;
        try {
            reader = new InputStreamReader(context.getAssets().open("style.css"), "UTF-8");
            BufferedReader br = new BufferedReader(reader);
            String line;
            while ((line = br.readLine()) != null) {
                contents.append(line);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "<style>" + contents.toString().trim().replace("\n", "") + "</style>";
    }

    public String injectCss(String page) {
        if (css == null) {
            css = buildCss();
        }
        int headEnd = page.indexOf("</head>");
        String res = "";
        if (headEnd > 0) {
            res = page.substring(0, headEnd) + css + page.substring(headEnd, page.length());
        } else {
            res = "<head>" + css + "</head>" + page;
        }
        return res;
    }
}
